package com.common.android.utils.db;

import com.common.android.utils.smiley.SmileyHistoryTable;
import com.product.android.business.ApplicationVariable;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;


public enum CommonDatabase {
	INSTANCE;
    private final String DATABASE_NAME = "91uchat_common";
    private final int DATABASE_VERSION =1; 
    
    private DatabaseHelper mOpenHelper = null;
    private SQLiteDatabase mDatabase;
    private String mDataBaseName=DATABASE_NAME;
    
    /**
     * SQLiteOpenHelper
     */
    private class DatabaseHelper extends SQLiteOpenHelper {
        public DatabaseHelper(Context context, String name,CursorFactory factory, int version) {
            super(context, name, factory, version);
        }

        public DatabaseHelper(Context context) {
            this(context, mDataBaseName, DATABASE_VERSION);
        }

        public DatabaseHelper(Context context, String name, int version) {
            this(context, name, null, version);
        }

        @Override
        /**
         * 创建数据库信息
         */
        public void onCreate(SQLiteDatabase db) {
        	//历史表情
            db.execSQL(SmileyHistoryTable.CREATE_TABLE);
            db.execSQL(SmileyHistoryTable.CREATE_INDEX);
        }

        @Override
        public synchronized void close() {
            super.close();
        }

        @Override
        public void onOpen(SQLiteDatabase db) {
            super.onOpen(db);
        }

        @Override
        /**
         * 数据库升级
         */
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        }
    }

    /**
     * @n<b>函数名称</b>     :close
     * @brief 关闭数据库（切换用户时调用）
     * @see
     * @version    Ver 1.3.x
     * @param  
     * @return void
     * @<b>作者</b>          :  cb
     * @<b>创建时间</b>      :  2013-12-20下午6:26:53      
    */
    public void close() {
    	if (mDatabase!=null){
    		mDatabase.close();	
    	}
    	mDatabase=null;
    	if (mOpenHelper!=null){
    		mOpenHelper.close();	
    	}
    	mOpenHelper=null;
    }
    
    public SQLiteDatabase getDb(){
    	if (mOpenHelper==null || mDatabase==null){
    		mDataBaseName=DATABASE_NAME+"_"+ApplicationVariable.INSTANCE.getIUser().getOapUid();
            mOpenHelper = new DatabaseHelper(ApplicationVariable.INSTANCE.applicationContext);
            mDatabase=mOpenHelper.getWritableDatabase();	
    	}
    	return mDatabase;
    }
    
    public String getDbName(){
    	return mDataBaseName;
    }
}